package csu.web.mypetstore.controller;

import csu.web.mypetstore.domain.Cart;
import csu.web.mypetstore.domain.CartItem;
import csu.web.mypetstore.pojo.Account;
import csu.web.mypetstore.pojo.Item;

import csu.web.mypetstore.service.CartService;
import csu.web.mypetstore.service.ItemService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Iterator;

@Controller
public class ItemController {

    @Autowired
    private ItemService itemService;
    @Autowired
    private CartService cartService;



    @GetMapping("addItemToCart")
    @Transactional
    public String addItemToCart(@RequestParam("workingItemId") String workingItemId, HttpSession session) {



        // 从Session中获取购物车对象
        Cart cart = (Cart) session.getAttribute("cart");
        if (cart == null) {
            cart = new Cart();
        }

        // 获取登录账户信息
        Account loginAccount = (Account) session.getAttribute("loginAccount");

        if (loginAccount == null) {
            return "account/signon";
        }
        String userId = (loginAccount != null) ? loginAccount.getUsername() : null;


        try {

            if (cart.containsItemId(workingItemId)) {
                // 如果购物车已有该商品，增加数量
                cart.incrementQuantityByItemId(workingItemId);
                cartService.updateQuantity(cart.getQuantityByItemId(workingItemId)+1,workingItemId,userId);
            } else {
                // 检查库存并添加新商品
                boolean isInStock = itemService.isItemInStock(workingItemId);
                Item item = itemService.getItem(workingItemId);
                cart.addItem(item, isInStock);

                cartService.insertCart(workingItemId,cart.getProductIdByItemId(workingItemId),cart.getDecriptionByItemId(workingItemId),true,cart.getQuantityByItemId(workingItemId),cart.getPriceByItemId(workingItemId).doubleValue(),cart.getPriceByItemId(workingItemId).doubleValue(),userId);
            }

        } catch (Exception e) {
            e.printStackTrace(); // 在实际应用中应使用日志框架记录异常
        }

        // 更新Session中的购物车
        session.setAttribute("cart", cart);

        // 返回视图名称，Spring会自动解析为/WEB-INF/jsp/cart/cart.jsp（取决于视图解析器配置）
        return "cart/cart";
    }
    @GetMapping("removeCartItem")
    @Transactional
    public String removeItemFromCart(@RequestParam("workingItemId") String workingItemId, HttpSession session) {
        // 从Session中获取购物车对象
        Cart cart = (Cart) session.getAttribute("cart");

        // 获取登录账户信息
        Account loginAccount = (Account) session.getAttribute("loginAccount");
        String username = (loginAccount != null) ? loginAccount.getUsername() : null;
        String userId = username;

        // 从购物车中移除商品
        Item item = cart.removeItemById(workingItemId);
        if (item == null) {
            session.setAttribute("errorMessage", "Attempted to remove null CartItem from Cart.");
            return "common/error"; // 返回错误页面
        } else {
            try {

                // 记录用户行为
                String action = "Remove_Item_From_Cart";

                // 执行数据库删除操作
                cartService.deleteItem(workingItemId,userId);


            } catch (Exception e) {
                e.printStackTrace(); // 建议使用日志框架记录异常
            }
        }

        // 返回购物车视图
        return "cart/cart";
    }
    @GetMapping("updateCartJSServlet")
    @Transactional
    public String updateCartJS(@RequestParam("quantity") String quantityParam, @RequestParam("workingItemId") String itemId, HttpSession session) {
        // 从Session中获取购物车


        System.out.println("--------------updateCartJSServlet-----------------");


        Cart cart = (Cart) session.getAttribute("cart");
        if (cart == null) {
            cart = new Cart();
            session.setAttribute("cart", cart);
        }

        cart.setQuantityByItemId(itemId, Integer.parseInt(quantityParam));
        cartService.updateQuantity(Integer.parseInt(quantityParam),itemId,((Account) session.getAttribute("loginAccount")).getUsername());

//        // 更新购物车中所有商品的数量
//        Iterator<CartItem> cartItemIterator = cart.getAllCartItems();
//        while (cartItemIterator.hasNext()) {
//            CartItem cartItem = cartItemIterator.next();
//            String itemid = cartItem.getItem().getItemid();
//
//            try {
//                int quantity = Integer.parseInt(quantityParam); // 假设前端发送单一quantity参数
//                cart.setQuantityByItemId(itemid, quantity);
//                if (quantity < 1) {
//                    cartItemIterator.remove();
//                }
//            } catch (Exception e) {
//                e.printStackTrace(); // 建议使用日志框架记录异常
//            }
//        }
        session.setAttribute("cart", cart);

        // 返回字符串（模拟原Servlet的text/xml输出）
        return "cart/cart";
    }
    @PostMapping("addNewItem")
    @Transactional
    public String addItem(
            HttpSession session,
            @RequestParam BigDecimal listPrice,
            @RequestParam double unitcost,
            @RequestParam String supplier,
            @RequestParam int inventory,
            @RequestParam String attribute1,
            @RequestParam String attribute2,
            @RequestParam String attribute3,
            @RequestParam String attribute4,
            @RequestParam String attribute5) {

         String productId=(String)session.getAttribute("productId");
         Item item=new Item();
          item.setItemid("EST-"+System.currentTimeMillis());
          item.setListprice(listPrice.doubleValue());
          item.setUnitcost((int) unitcost);
          item.setSupplier(Integer.parseInt(supplier));
          item.setStatus("P");
          item.setSupplier(Integer.parseInt(supplier));
          item.setAttr1(attribute1);
          item.setAttr2(attribute2);
          item.setAttr3(attribute3);
          item.setAttr4(attribute4);
          item.setAttr5(attribute5);
          item.setProductid(productId);
          itemService.insertItem(item,inventory);
          Item item1=itemService.getItem(item.getItemid());
          itemService.updateInventory(item1.getItemid(),"EST-"+item1.getId(),inventory);
          item1.setItemid("EST-"+item1.getId());
          //System.out.println("-------------"+item1.getItemid()+"----------------");
          itemService.updateItem(item1);





        return "redirect:/cmsProductForm?productId="+productId;
    }



    @PostMapping("updateItem")
    @Transactional
    public String updateItem(
            HttpSession session,
            @RequestParam("itemid") String itemId,
            @RequestParam BigDecimal listPrice,
            @RequestParam double unitcost,
            @RequestParam String supplier,
            @RequestParam int inventory,
            @RequestParam String attribute1,
            @RequestParam String attribute2,
            @RequestParam String attribute3,
            @RequestParam String attribute4,
            @RequestParam String attribute5
           ) {  // 使用RedirectAttributes传递消息


        String productId=(String)session.getAttribute("productId");
        Item item=itemService.getItem(itemId);
        item.setItemid(itemId);
        item.setListprice(listPrice.doubleValue());
        item.setUnitcost((int)unitcost);
        item.setSupplier(Integer.parseInt(supplier));
        item.setQuantity(Integer.valueOf(inventory));
        item.setAttr1(attribute1);
        item.setAttr2(attribute2);
        item.setAttr3(attribute3);
        item.setAttr4(attribute4);
        item.setAttr5(attribute5);
        itemService.updateItem(item);
        // 这里添加保存到数据库的逻辑
        return "redirect:/cmsProductForm?productId="+productId;
    }
    @GetMapping("increaseInventory")
    @Transactional
    public String increaseInventory(@RequestParam("workingItemId") String workingItemId, HttpSession session) {
        // 增加库存数量，默认增加1
        itemService.increaseItemNum(1, workingItemId);

        // 获取当前商品所属的产品ID，用于重定向回产品页面
        Item item = itemService.getItem(workingItemId);
        String productId = item.getProductid();

        // 重定向回产品页面
        return "redirect:/cmsProductForm?productId=" + productId;
    }
    @GetMapping("decreaseInventory")
    @Transactional
    public String decreaseInventory(@RequestParam("workingItemId") String workingItemId, HttpSession session) {
        // 减少库存数量，默认减少1
        itemService.decreaseItemNum(1, workingItemId);

        // 获取当前商品所属的产品ID，用于重定向回产品页面
        Item item = itemService.getItem(workingItemId);
        String productId = item.getProductid();

        // 重定向回产品页面
        return "redirect:/cmsProductForm?productId=" + productId;
    }
    @GetMapping("increaseInventoryByAmount")
    @Transactional
    public String increaseInventoryByAmount(
            @RequestParam("workingItemId") String workingItemId,
            @RequestParam("amount") int amount,
            HttpSession session,
            @RequestHeader(value = "Referer", required = false) String referer) {
        // 增加指定数量的库存
        if (amount > 0) {
            itemService.increaseItemNum(amount, workingItemId);
        }

        // 如果有Referer，则返回到来源页面
        if (referer != null && !referer.isEmpty()) {
            return "redirect:" + referer;
        }

        // 否则返回到商品列表页面
        Item item = itemService.getItem(workingItemId);
        String productId = item.getProductid();
        return "redirect:/cmsProductForm?productId=" + productId;
    }

    @GetMapping("decreaseInventoryByAmount")
    @Transactional
    public String decreaseInventoryByAmount(
            @RequestParam("workingItemId") String workingItemId,
            @RequestParam("amount") int amount,
            HttpSession session,
            @RequestHeader(value = "Referer", required = false) String referer) {
        // 减少指定数量的库存
        if (amount > 0) {
            itemService.decreaseItemNum(amount, workingItemId);
        }

        // 如果有Referer，则返回到来源页面
        if (referer != null && !referer.isEmpty()) {
            return "redirect:" + referer;
        }

        // 否则返回到商品列表页面
        Item item = itemService.getItem(workingItemId);
        String productId = item.getProductid();
        return "redirect:/cmsProductForm?productId=" + productId;
    }
    private String getRedirectUrl(HttpSession session) {
        String productId = (String) session.getAttribute("productId");
        return "redirect:/cmsProductForm?productId=" + (productId != null ? productId : "");
    }
    @GetMapping("removeItem")
    @Transactional
    public String removeItem(@RequestParam("workingItemId") String workingItemId, HttpSession session){

         String productId=(String)session.getAttribute("productId");
        itemService.removeItem(workingItemId);


        return "redirect:/cmsProductForm?productId=" + productId;
    }


}




